//
//  MaintenanceTypeViewController.m
//  FMS
//
//  Created by Steven on 10/16/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "MaintenanceTypeViewController.h"
#import "MaintenanceMgmtViewController.h"
#import "MaintenanceDetailedViewController.h"
#import "BuildingMgmtViewController.h"
#import "DetailedItemViewController.h"

@interface MaintenanceTypeViewController ()

@end

@implementation MaintenanceTypeViewController
@synthesize parent;
@synthesize itemDetailedDict;
@synthesize itemType;
@synthesize inputInspectionDict;
@synthesize theNewInspectionId,theNewScheduleId;
@synthesize beforeInspectionSavedDict,beforeScheduleSavedDict;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil serviceType:(int)_serviceType parent:(id)_parent;
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        serviceType  = _serviceType;
        parent = _parent;
    }
    return self;
}

- (IBAction)backPreviousView:(id)sender {
    NSError *error;
    if (theNewInspectionId != nil) {
        [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:theNewInspectionId error:&error];
        if (!error) {
            NSLog(@"delete temporary new inspection successfully");
        }
        
        //reload previous inspection
        if (beforeInspectionSavedDict != nil) {
            NSError *error;
            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:beforeInspectionSavedDict error:&error];
            if (!error) {
                NSLog(@"reload previous Inspection successfully");
            }
        }
    }
    
    if (theNewScheduleId != nil) {
        [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:theNewScheduleId error:&error];
        if (!error) {
            NSLog(@"delete temporary new schedule successfully");
        }
        
        //reload previous schedule
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:beforeScheduleSavedDict error:&error];
        if (!error) {
            NSLog(@"reload previous Schedule successfully");
        }
    }
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationController.navigationBar.hidden = YES;
    
    _mainTableView.separatorColor = APPLE_BLUE_COLOR;
    
    mainArray = [NSMutableArray arrayWithCapacity:1];
    arrayOriginal = [NSMutableArray arrayWithCapacity:1];
    
    //check if this view was loaded from Add New Inspection with Failed status
    if ([parent isKindOfClass:[MaintenanceDetailedViewController class]]) {
//        _btnBack.hidden = YES;
        //just loaded Maintenance type
        _lbMainTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.add-new.select-maintenance-type"];
        
        /*
        //only 2 maintenance type is CM Work (below cost cap) and AWS
        NSString *itemName[] = {
            [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm"],
            [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.aws"],
        };
        NSString *_itemType[] = {
            [NSString stringWithFormat:@"%d",CM],
            [NSString stringWithFormat:@"%d",AWS],
        };
        
        NSString *itemLevel[] = {
            [NSString stringWithFormat:@"%d",0],
            [NSString stringWithFormat:@"%d",0],
        };
        
        for (int i=0;i < sizeof(itemName)/sizeof(itemName[0]);i++){
            NSMutableDictionary *dict;
            if (i > 0) {
                //AWS
                NSString *subItemName[] = {
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pms"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-above-cost-cap"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-not-under-pmws"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-above-70"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-below-70"],
                };
                NSString *subItemType[] = {
                    [NSString stringWithFormat:@"%d",PMS],
                    [NSString stringWithFormat:@"%d",CM_Above_Cost_Cap],
                    [NSString stringWithFormat:@"%d",CM_Not_Under_PMWS],
                    [NSString stringWithFormat:@"%d",New_Works_Above_70],
                    [NSString stringWithFormat:@"%d",New_Works_Below_70]
                };
                
                NSString *subItemLevel[] = {
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                };
                
                NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:1];
                for (int i=0;i < sizeof(subItemName)/sizeof(subItemName[0]);i++){
                    NSMutableDictionary *subDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",subItemName[i],@"itemName",subItemType[i],@"itemType",subItemLevel[i],@"itemLevel", nil];
                    [tmpArray addObject:subDict];
                }
                
                dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",itemName[i],@"itemName",_itemType[i],@"itemType",itemLevel[i],@"itemLevel",tmpArray,@"subMaintenanceArray", nil];
            }
            else
                dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",itemName[i],@"itemName",_itemType[i],@"itemType",itemLevel[i],@"itemLevel", nil];
            [arrayOriginal addObject:dict];
        }
         */
        NSString *itemName[] = {
            [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pmws"],
            [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.aws"]
        };
        {
            /************ init value for PMWS *************/
            //add 2 objects: PM & CM below cost cap to PMWS
            NSString *subItemName[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pm"],
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm"],
            };
            NSString *subItemType[] = {
                [NSString stringWithFormat:@"%d",PM],
                [NSString stringWithFormat:@"%d",CM],
            };
            
            NSString *subItemLevel[] = {
                [NSString stringWithFormat:@"%d",1],
                [NSString stringWithFormat:@"%d",1],
            };
            
            NSMutableArray *tmpArray1 = [NSMutableArray arrayWithCapacity:1];
            for (int i=0;i < sizeof(subItemName)/sizeof(subItemName[0]);i++){
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",subItemName[i],@"itemName",subItemType[i],@"itemType",subItemLevel[i],@"itemLevel", nil];
                [tmpArray1 addObject:dict];
            }
            
            NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",[NSNumber numberWithInt:PMWS],@"itemType",itemName[0],@"itemName",[NSNumber numberWithInt:0],@"itemLevel",tmpArray1,@"subMaintenanceArray", nil];
            [arrayOriginal addObject:dict1];
        }
        /*********** end init data for PMWS ************/
        
        /*********** init data for AWS *****************/
        {
            NSString *subItemName[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pms"],
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-above-cost-cap"],
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-not-under-pmws"],
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-above-70"],
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-below-70"],
            };
            NSString *subItemType[] = {
                [NSString stringWithFormat:@"%d",PMS],
                [NSString stringWithFormat:@"%d",CM_Above_Cost_Cap],
                [NSString stringWithFormat:@"%d",CM_Not_Under_PMWS],
                [NSString stringWithFormat:@"%d",New_Works_Above_70],
                [NSString stringWithFormat:@"%d",New_Works_Below_70]
            };
            
            NSString *subItemLevel[] = {
                [NSString stringWithFormat:@"%d",1],
                [NSString stringWithFormat:@"%d",1],
                [NSString stringWithFormat:@"%d",1],
                [NSString stringWithFormat:@"%d",1],
                [NSString stringWithFormat:@"%d",1],
            };
            
            NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:1];
            for (int i=0;i < sizeof(subItemName)/sizeof(subItemName[0]);i++){
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",subItemName[i],@"itemName",subItemType[i],@"itemType",subItemLevel[i],@"itemLevel", nil];
                [tmpArray addObject:dict];
            }
            
            NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",[NSNumber numberWithInt:AWS],@"itemType",itemName[1],@"itemName",[NSNumber numberWithInt:0],@"itemLevel",tmpArray,@"subMaintenanceArray",nil];
            [arrayOriginal addObject:dict2];
        }
    }
    else {
        if (serviceType == Inspection) {
            _lbMainTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.add-new.select-service-type"];
            
            NSString *itemName[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"],
                [dictLanguage objectForKey:@"maintenance-mgmt.service-type.maintenance"]
            };
            for (int i=0;i < sizeof(itemName)/sizeof(itemName[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:i+1],@"serviceType",itemName[i],@"itemName", nil];
                [arrayOriginal addObject:dict];
            }
        }
        else {
            _lbMainTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.add-new.select-maintenance-type"];
            
            NSString *itemName[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pmws"],
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.aws"]
            };
            {
            /************ init value for PMWS *************/
            //add 2 objects: PM & CM below cost cap to PMWS
            NSString *subItemName[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pm"],
                [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm"],
            };
            NSString *subItemType[] = {
                [NSString stringWithFormat:@"%d",PM],
                [NSString stringWithFormat:@"%d",CM],
            };
            
            NSString *subItemLevel[] = {
                [NSString stringWithFormat:@"%d",1],
                [NSString stringWithFormat:@"%d",1],
            };
            
            NSMutableArray *tmpArray1 = [NSMutableArray arrayWithCapacity:1];
            for (int i=0;i < sizeof(subItemName)/sizeof(subItemName[0]);i++){
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",subItemName[i],@"itemName",subItemType[i],@"itemType",subItemLevel[i],@"itemLevel", nil];
                [tmpArray1 addObject:dict];
            }
            
            NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",[NSNumber numberWithInt:PMWS],@"itemType",itemName[0],@"itemName",[NSNumber numberWithInt:0],@"itemLevel",tmpArray1,@"subMaintenanceArray", nil];
            [arrayOriginal addObject:dict1];
            }
            /*********** end init data for PMWS ************/
            
            /*********** init data for AWS *****************/
            {
                NSString *subItemName[] = {
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pms"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-above-cost-cap"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-not-under-pmws"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-above-70"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-below-70"],
                };
                NSString *subItemType[] = {
                    [NSString stringWithFormat:@"%d",PMS],
                    [NSString stringWithFormat:@"%d",CM_Above_Cost_Cap],
                    [NSString stringWithFormat:@"%d",CM_Not_Under_PMWS],
                    [NSString stringWithFormat:@"%d",New_Works_Above_70],
                    [NSString stringWithFormat:@"%d",New_Works_Below_70]
                };
                
                NSString *subItemLevel[] = {
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                    [NSString stringWithFormat:@"%d",1],
                };
                
                NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:1];
                for (int i=0;i < sizeof(subItemName)/sizeof(subItemName[0]);i++){
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",subItemName[i],@"itemName",subItemType[i],@"itemType",subItemLevel[i],@"itemLevel", nil];
                    [tmpArray addObject:dict];
                }
                
                NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"serviceType",[NSNumber numberWithInt:AWS],@"itemType",itemName[1],@"itemName",[NSNumber numberWithInt:0],@"itemLevel",tmpArray,@"subMaintenanceArray",nil];
                [arrayOriginal addObject:dict2];
            }
        }
    }
    
    [mainArray addObjectsFromArray:arrayOriginal];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (SYSTEM_VERSION_LESS_THAN(@"7.0")) ;
    else
        self.navigationController.view.superview.bounds = CGRectMake(0, 0, 400, 400);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [mainArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    UILabel *lbCell = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 300, 21)];
    lbCell.backgroundColor = [UIColor clearColor];
    lbCell.textColor = [UIColor darkGrayColor];
    lbCell.text = [dict objectForKey:@"itemName"];
    [cell.contentView addSubview:lbCell];
    
    //check sub type or main type
    int level = [[dict objectForKey:@"itemLevel"] intValue];
    if (level > 0)
        lbCell.frame = CGRectMake(40, 5, 300, 21);
    
    if (serviceType == Maintenance) {
        int indexType = [[dict objectForKey:@"itemType"] intValue];
        if (indexType == PMWS || indexType == AWS) {
            UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
            imgView.tag = 100;
            imgView.frame = CGRectMake(370, 20, 13, 8);
            imgView.transform = CGAffineTransformMakeRotation(-M_PI*2.5);
            [cell.contentView addSubview:imgView];
        }
    }

    return cell;
}

#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    if (serviceType == Inspection) {
        [self dismissModalViewControllerAnimated:NO];
        [self performSelector:@selector(delayToDismiss:) withObject:dict afterDelay:0.5];
    }
    else {
        NSDictionary *d = [mainArray objectAtIndex:indexPath.row];
        if([d valueForKey:@"subMaintenanceArray"]) {
            //rotate the icon drop down
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            UIImageView *imgDropDown = (UIImageView*)[cell.contentView viewWithTag:100];
            imgDropDown.transform = CGAffineTransformMakeRotation(-M_PI*2.0);
            
            NSArray *ar = [d valueForKey:@"subMaintenanceArray"];
            
            BOOL isAlreadyInserted=NO;
            
            for(NSDictionary *dInner in ar ){
                NSInteger index = [mainArray indexOfObjectIdenticalTo:dInner];
                isAlreadyInserted = (index>0 && index!=NSIntegerMax);
                if(isAlreadyInserted) break;
            }
            
            if(isAlreadyInserted) {
                //rotate the icon drop down
                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                UIImageView *imgDropDown = (UIImageView*)[cell.contentView viewWithTag:100];
                imgDropDown.transform = CGAffineTransformMakeRotation(-M_PI*2.5);
                
                [self miniMizeThisRows:ar];
            }
            else {
                NSUInteger count = indexPath.row+1;
                NSMutableArray *arCells = [NSMutableArray array];
                for(NSDictionary *dInner in ar ) {
                    [arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
                    [mainArray insertObject:dInner atIndex:count++];
                }
                [tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
            }
        }
        else {
            //select the row doesn't have sub item
            NSLog(@"index = %@",[mainArray objectAtIndex:indexPath.row]);
            [self dismissModalViewControllerAnimated:NO];
            [self performSelector:@selector(delayToSelectMaintenanceType:) withObject:dict afterDelay:0.5];
        }
    }
}

-(void)miniMizeThisRows:(NSArray*)ar{
	
	for(NSDictionary *dInner in ar ) {
		NSUInteger indexToRemove=[mainArray indexOfObjectIdenticalTo:dInner];
		NSArray *arInner=[dInner valueForKey:@"subMaintenanceArray"];
		if(arInner && [arInner count]>0){
			[self miniMizeThisRows:arInner];
		}
		
		if([mainArray indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
			[mainArray removeObjectIdenticalTo:dInner];
			[_mainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:
                                                    [NSIndexPath indexPathForRow:indexToRemove inSection:0]
                                                    ]
                                  withRowAnimation:UITableViewRowAnimationRight];
		}
	}
}

- (void) delayToDismiss:(NSMutableDictionary*)dict {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *maintenancePermissionDict = [userDefaults objectForKey:MAINTENANCE_PERMISSION];
    NSMutableDictionary *permissionDict;
    
    int _itemType = [[dict objectForKey:@"serviceType"] intValue];
    if (_itemType == Inspection) {
        permissionDict = [maintenancePermissionDict objectForKey:@"inspection"];
    }
    else {
        permissionDict = [maintenancePermissionDict objectForKey:@"maintenance"];
    }
#ifndef vDEBUG
    BOOL isAdd = [[permissionDict objectForKey:@"add"] boolValue];
    if (!isAdd) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        
        return;
    }
#endif
    if ([parent isKindOfClass:[MaintenanceMgmtViewController class]])
        [(MaintenanceMgmtViewController*)parent confirmSelectType:dict];
    else if ([parent isKindOfClass:[DetailedItemViewController class]])
        [(DetailedItemViewController*)parent confirmSelectType:dict];
}

- (void) delayToSelectMaintenanceType:(NSMutableDictionary*)dict {
    //check situation when select Maintenance in adding new.
    if ([parent isKindOfClass:[BuildingMgmtViewController class]]){
        [(BuildingMgmtViewController*)parent confirmSelectMaintenance:dict itemDetailedDict:itemDetailedDict];
    }
    else if ([parent isKindOfClass:[MaintenanceDetailedViewController class]]){
        //situation add new with Inspection type and Failed
        if (inputInspectionDict != nil)
            ((MaintenanceDetailedViewController*)parent).inputInspectionDict = inputInspectionDict;
        [(MaintenanceDetailedViewController*)parent initNewControllerBeforeConfirmMaintenance:dict itemDetailedDict:itemDetailedDict];
    }
    else if ([parent isKindOfClass:[DetailedItemViewController class]]) {
        [(DetailedItemViewController*)parent confirmSelectMaintenance:dict itemDetailedDict:itemDetailedDict];
    }
}


@end
